package com.panopset.nls;

import static com.panopset.Util.PANSOPSET_USER_DIR;
import static com.panopset.Util.PATH_SEP;
import static com.panopset.Util.dropExtension;
import static com.panopset.Util.isPopulated;
import static com.panopset.Util.log;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.ImageIcon;

import com.panopset.gui.SpritePackage;

/**
 * Flag icons available in flywheel.jar.
 *
 * @author Karl Dinwiddie
 *
 */
public class FlagIcons {
    public final SpritePackage spritePackage = new SpritePackage(
    "/com/panopset/nls/flagicons.jar");
    private final String JAR_PATH = PANSOPSET_USER_DIR + PATH_SEP + "flagIcons";
    private static FlagIcons singleton;
    private Map<String, ImageIcon> flags;

    private FlagIcons() {
        try {
            spritePackage.saveResourcesToDirectory(JAR_PATH);
        } catch (IOException e) {
            log(e);
        }
    }

    public ImageIcon getFlag(String localeName) {
        if (flags == null) {
            flags = new HashMap<String, ImageIcon>();
            String d = JAR_PATH + PATH_SEP;
            for (String ln : spritePackage.getResourceList()) {
                flags.put(ln, new ImageIcon(d + ln + ".png"));
            }
        }
        return flags.get(localeName);
    }

    public static FlagIcons asFlagIcons() {
        if (singleton == null) {
            singleton = new FlagIcons();
        }
        return singleton;
    }

    /**
     * Check to see if an NLS code has a corresponding flag icon.
     * @param nlsCode, ie: en, fr, de etc.
     * @return true if there is a flag icon available for nlsCode
     */
    public boolean isValidNlsCode(String nlsCode) {
        if (!isPopulated(nlsCode)) {
            return false;
        }
        if (spritePackage.getResourceList().contains(nlsCode)) {
            return true;
        } else {
            log("Flag icon not found for " + nlsCode);
            return false;
        }
    }

    /**
     * Check to see if an NLS properties file has a corresponding flag icon.
     * @param propertiesFile, ie: en.properties
     * @return true if there is a flag icon available for propertiesFile.
     */
    public boolean isValidProperiesFile(File propertiesFile) {
        if (propertiesFile == null) {
            return false;
        }
        if (propertiesFile.isDirectory()) {
            return false;
        }
        return isValidNlsCode(dropExtension(propertiesFile.getName()));
    }

}
